﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace OrderControl {
    public class OrderService {
        private static OrderService instance = new OrderService();

        private List<Order> orders = new List<Order>();

        public enum SearchType { Id, Commodity, Customer, Price };

        public static OrderService Instance { get => instance; }

        public List<Order> Orders { get => orders; }

        private OrderService() { }

        public void Add(Order newOrder) {
            if (newOrder == null) {
                throw new ArgumentNullException(nameof(newOrder));
            }
            foreach (Order order in Orders) {
                if (order.Equals(newOrder)) {
                    throw new OrderAddException("Identical order id is not allowed!");
                }
            }
            Orders.Add(newOrder);
        }

        public void Delete(int id) {
            if (!Orders.Remove(Orders.Where(order => order.Id == id).FirstOrDefault())) {
                throw new OrderDeleteException("Order not found.");
            }
        }

        public void DetailAdd(Order order, Commodity commodity, int amount) {
            foreach (OrderDetail detail in order.Details) {
                if (detail.Commodity == commodity) {
                    throw new OrderModifyException("Same commodity is not allowed!");
                }
            }
            order.Details.Add(new OrderDetail(commodity, amount));
        }

        public void DetailDelete(Order order, Commodity commodity) {
            if (!order.Details.Remove(order.Details.Where(order => order.Commodity == commodity).FirstOrDefault())) {
                throw new OrderDeleteException("Commodity is not found!");
            }
        }

        public void DetailModify(Order order, Commodity commodity, int amount) {
            if (amount < 0) {
                throw new OrderModifyException("Amount cannot be less than zero.");
            }
            foreach (OrderDetail detail in order.Details) {
                if (detail.Commodity == commodity) {
                    if (amount == 0) {
                        order.Details.Remove(detail);
                    }
                    else {
                        detail.Amount = amount;
                    }
                    return;
                }
            }
            throw new OrderModifyException("Commodity is not found!");
        }

        public IEnumerable<Order> Search(SearchType type, object key) {
            IEnumerable<Order> result = null;
            switch (type) {
                case SearchType.Id:
                    result = SearchById(key);
                    break;
                case SearchType.Commodity:
                    result = SearchByCommodity(key);
                    break;
                case SearchType.Customer:
                    result = SearchByCustomer(key);
                    break;
                case SearchType.Price:
                    result = SearchByPrice(key);
                    break;
            }
            if (!result.Any()) {
                throw new OrderSearchException("No qualified order.");
            }
            return result;
        }

        private IEnumerable<Order> SearchById(object key) {
            if (key is int id) {
                return from order in Orders
                       where order.Id == id
                       orderby order.Id
                       select order;
            }
            else {
                throw new OrderSearchException("Malformed Id!");
            }
        }

        private IEnumerable<Order> SearchByCommodity(object key) {
            if (key is string commodityName) {
                return from order in Orders
                       where order.Details.Any(detail => detail.Commodity.Name == commodityName)
                       orderby order.Id
                       select order;
            }
            else {
                throw new OrderSearchException("Malformed Commodity Name!");
            }
        }
        private IEnumerable<Order> SearchByCustomer(object key) {
            if (key is string customerName) {
                return from order in Orders
                       where order.Customer.Name == customerName
                       orderby order.Id
                       select order;
            }
            else {
                throw new OrderSearchException("Malformed Customer Name!");
            }
        }
        private IEnumerable<Order> SearchByPrice(object key) {
            if (key is double totalPrice) {
                return from order in Orders
                       where order.TotalPrice == totalPrice
                       orderby order.Id
                       select order;
            }
            else {
                throw new OrderSearchException("Malformed Price!");
            }
        }

        public void Sort() {
            Orders.Sort((orderA, orderB) => orderA.Id - orderB.Id);
        }

        public void Sort(Func<Order, Order, int> func) {
            Orders.Sort((orderA, orderB) => func(orderA, orderB));
        }

        public static void Export() {
            using (FileStream fs = new FileStream("OrderService.xml", FileMode.Create)) {
                XmlSerializer serializer = new XmlSerializer(typeof(OrderService));
                serializer.Serialize(fs, instance);
            }
        }

        public static void Import() {
            using (FileStream fs = new FileStream("OrderService.xml", FileMode.Open)) {
                XmlSerializer serializer = new XmlSerializer(typeof(OrderService));
                instance = (OrderService)serializer.Deserialize(fs);
            }
        }
    }
}
